import TIM from "tim-wx-sdk";
import TIMUploadPlugin from "tim-upload-plugin";
import Vue from "vue";
import {
	followAdd,
	getAppId
} from "@/api/im";
import { getStorage } from "./auth";

export function formateTime(secondTime) {
	const time = secondTime;
	let newTime;
	let hour;
	let minite;
	let seconds;
	if (time >= 3600) {
		hour = parseInt(time / 3600) < 10 ? `0${parseInt(time / 3600)}` : parseInt(time / 3600);
		minite = parseInt(time % 60 / 60) < 10 ? `0${parseInt(time % 60 / 60)}` : parseInt(time % 60 / 60);
		seconds = time % 3600 < 10 ? `0${time % 3600}` : time % 3600;
		if (seconds > 60) {
			minite = parseInt(seconds / 60) < 10 ? `0${parseInt(seconds / 60)}` : parseInt(seconds / 60);
			seconds = seconds % 60 < 10 ? `0${seconds % 60}` : seconds % 60;
		}
		newTime = `${hour}:${minite}:${seconds}`;
	} else if (time >= 60 && time < 3600) {
		minite = parseInt(time / 60) < 10 ? `0${parseInt(time / 60)}` : parseInt(time / 60);
		seconds = time % 60 < 10 ? `0${time % 60}` : time % 60;
		newTime = `00:${minite}:${seconds}`;
	} else if (time < 60) {
		seconds = time < 10 ? `0${time}` : time;
		newTime = `00:00:${seconds}`;
	}
	return newTime;
}
export function getToAccount(conversation) {
	if (!conversation || !conversation.conversationID) {
		return '';
	}
	const type = conversation.conversationType ? conversation.conversationType : conversation.type
	switch (type) {
		case 'C2C':
			return conversation.conversationID.replace('C2C', '');

		case 'GROUP':
			return conversation.conversationID.replace('GROUP', '');

		default:
			return conversation.conversationID;
	}
}
export function getPhoneByImUserID(userID) {
	return userID.replace('dhs_personal_', '').replace('dhs_enterprise_', '');
}
/**
 * @description 该方法返回一个promise对象，请注意使用then，catch捕获并进行逻辑处理
 * @description catch回调只有一个参数，即为错误信息提示，可以使用element-ui提示错误消息
 * @description then回调中请自行跳转至im页面
 * @description 请注意判断发送对象，因hr和求职者im账号独立，采用前缀拼接手机号方式作为账号，方法中自动获取当前身份相反的前缀拼接手机号进行发送，例如当前为hr，就会像角色为求职者的手机号发送，反之亦然
 * @param message
 * @param toPhone
 * @returns {Promise<unknown>}
 */

export function sendHiMessage(message, toPhone,positionId) {
	return new Promise((resolve, reject) => {
		if (typeof message != 'string') {
			reject('message 参数错误 需要的是string 传入的是' + typeof message)
		}
		if (!['number', 'string'].includes(typeof toPhone)) {
			reject('toPhone 参数错误 需要的是number/string 传入的是' + typeof toPhone)
		}
		if (message.length === 0) {
			reject('message内容不能为空')
		}
		toPhone = toPhone.toString();
		if (toPhone.length !== 11) {
			reject('toPhone 参数长度错误')
		}
		const userIdentity = getStorage('identity');
		const to = userIdentity == 1 ? 'dhs_enterprise_' + toPhone : 'dhs_personal_' + toPhone;
		const messageContext = uni.$TUIKit.createTextMessage({
			to,
			conversationType: TIM.TYPES.CONV_C2C,
			payload: {
				text: message
			}
		})
		const positionMessage = uni.$TUIKit.createCustomMessage({
			to,
			conversationType: TIM.TYPES.CONV_C2C,
			payload: {
				data: 'position',
				description: '',
				extension: JSON.stringify({id:positionId}),
			}
		})
		uni.showLoading({
			title: '发送中',
			mask: true
		})
		uni.$TUIKit.sendMessage(positionMessage).then((pres) => {
			setTimeout(()=>{
				uni.$TUIKit.sendMessage(messageContext).then((res) => {
					followAdd({
						follow: 3,
						mobile: toPhone,
						followType: userIdentity
					}).then((sRes) => {
						uni.navigateTo({
							url:'/page_other/chat/index?conversationID='+res.data.message.conversationID
						})
						resolve();
					}).catch((sRes) => {
						reject('消息发送成功 服务器同步失败');
					})
				}).catch(() => {
					uni.hideLoading()
					reject('消息发送失败')
				});
			},500)
		}).catch((pres) => {
			uni.hideLoading()
			reject('消息发送失败')
		});
		
	})
}

export function caculateTimeago(dateTimeStamp) {
	const minute = 1000 * 60; // 把分，时，天，周，半个月，一个月用毫秒表示

	const hour = minute * 60;
	const day = hour * 24;
	const week = day * 7;
	const now = new Date().getTime(); // 获取当前时间毫秒

	const diffValue = now - dateTimeStamp; // 时间差

	let result = '';

	if (diffValue < 0) {
		return;
	}

	const minC = diffValue / minute; // 计算时间差的分，时，天，周，月

	const hourC = diffValue / hour;
	const dayC = diffValue / day;
	const weekC = diffValue / week;

	if (weekC >= 1 && weekC <= 4) {
		result = ` ${parseInt(weekC, 10)}周前`;
	} else if (dayC >= 1 && dayC <= 6) {
		result = ` ${parseInt(dayC, 10)}天前`;
	} else if (hourC >= 1 && hourC <= 23) {
		result = ` ${parseInt(hourC, 10)}小时前`;
	} else if (minC >= 1 && minC <= 59) {
		result = ` ${parseInt(minC, 10)}分钟前`;
	} else if (diffValue >= 0 && diffValue <= minute) {
		result = '刚刚';
	} else {
		const datetime = new Date();
		datetime.setTime(dateTimeStamp);
		const Nyear = datetime.getFullYear();
		const Nmonth = datetime.getMonth() + 1 < 10 ? `0${datetime.getMonth() + 1}` : datetime.getMonth() + 1;
		const Ndate = datetime.getDate() < 10 ? `0${datetime.getDate()}` : datetime.getDate();
		result = `${Nyear}-${Nmonth}-${Ndate}`;
	}

	return result;
}
export function initIM() {
	return new Promise((resolve, reject) => {
		getAppId().then((res) => {
			const SDKAppID = res;
			Vue.prototype.$store.commit('user/SET_SDK_APP_ID',SDKAppID)
			let options = {
				SDKAppID
			}
			let tim = uni.$TUIKit = TIM.create(options);
			tim.setLogLevel(1);
			tim.registerPlugin({
				'tim-upload-plugin': TIMUploadPlugin
			});
			uni.$TUIKitTIM = TIM;
			uni.$TUIKitEvent = TIM.EVENT;
			uni.$TUIKitVersion = TIM.VERSION;
			uni.$TUIKitTypes = TIM.TYPES;
			wx.$TIM = uni.$TUIKit;
			tim.on(TIM.EVENT.SDK_READY, onSdkReady);
			tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
			tim.on(TIM.EVENT.MESSAGE_MODIFIED, onMessageModified);
			tim.on(TIM.EVENT.MESSAGE_REVOKED, onMessageRevoked);
			tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, onMessageReadByPeer);
			tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, onConversationListUpdated);
			tim.on(TIM.EVENT.PROFILE_UPDATED, onProfileUpdated);
			tim.on(TIM.EVENT.BLACKLIST_UPDATED, onBlacklistUpdated);
			tim.on(TIM.EVENT.FRIEND_LIST_UPDATED, onFriendListUpdated);
			tim.on(TIM.EVENT.FRIEND_GROUP_LIST_UPDATED, onFriendGroupListUpdated);
			tim.on(TIM.EVENT.KICKED_OUT, onKickedOut);
			resolve('初始化成功');
		}).catch((res) => {
			reject('IM初始化失败');
		})
	})
}

function onSdkReady() {
	uni.$TUIKit.updateMyProfile({
	    nick: Vue.prototype.$store.getters.user.realName, avatar: Vue.prototype.$store.getters.user.faceUrl
	})
	uni.$emit('onSdkReady');
}

function onMessageReceived(e) {
	uni.$emit('onMessageReceived', e);
}

function onMessageModified(e) {
	uni.$emit('onMessageModified', e);
}

function onMessageRevoked(e) {
	uni.$emit('onMessageRevoked', e);
}

function onMessageReadByPeer(e) {
	uni.$emit('onMessageReadByPeer', e);
}

function onConversationListUpdated(e) {
	uni.$emit('onConversationListUpdated', e);
}

function onProfileUpdated(e) {
	uni.$emit('onProfileUpdated', e);
}

function onBlacklistUpdated(e) {
	uni.$emit('onBlacklistUpdated', e);
}

function onFriendListUpdated(e) {
	uni.$emit('onFriendListUpdated', e);
}

function onFriendGroupListUpdated(e) {
	uni.$emit('onFriendGroupListUpdated', e);
}

function onKickedOut(e) {
	if (e.data.type !== TIM.TYPES.KICKED_OUT_REST_API) {
		uni.showModal({
			title: '提示',
			content:'您的账号在其他设备登录，您被迫下线',
			success(){
				uni.switchTab({
					url:'/pages/home/index'
				})
			}
		})
		Vue.prototype.$store.commit('user/SET_TOKEN',null)
		Vue.prototype.$store.commit('user/SET_USER',null)
	}
	uni.$emit('onKickedOut', e);
}
